Selections

Selections: if statement

Example: " If it is raining outside, then I carry umbrella."

In programming such logic is written using if statement.





Example 1 ( Condition with numeric )

        emirates = input(" How many emirates are in UAE? ")
        emirates = int(emirates)
        if(emirates == 7): 
            print(" Yes you are correct ")
        else:
            print(" No, there are 7 emirates ")
	    
Here is the code and its output:

Example 2 ( Condition with non numeric)

	capital = input(" What is capital of UAE? ")
        if(capital == " Abu Dhabi"): 
            print(" Yes you are correct ")
        else:
            print(" No, it is Abu Dhabi ")
	
Here is the code and its output:

Note: String comparision is case sensitive.

Example 3 ( Condition with non numeric )

Write a Python program to calculate the cost of insurance based on the age. If the age of the subscriber is more than or equal 40 years, the cost will be 500 each month, otherwise the cost is 300 a month.

	    age = input (" What is your age? ")
	    age = int(age)
	    
	    insurance = 0
	    
	    if (age >= 40):
	        insurance = 500
	    else: 
	        insurance = 300
	    
	    print (insurance)
	

Logical Operators

When you have more than one condition in the same if statement [compound condition], then you need to use a logical operator. These logical operators simply allow you to request that both conditions must be met or only one of them.

C1C2C1 and C2C1 or C2
falsefalse
false
false
falsetrue
false
true
truefalse
false
true
truetrue
true
true


OperatorDescriptionExample
andIf both the operands are true then condition becomes true.3 >7 and 2<3
orIf any of the two operands are non-z ero then condition becomes true7 > 7 or 2 < 3

Logical Operators ( 2 )

When you have more than one condition, it is recommended to group them using brackets.
Think of a situation when condition 1 to be met and one of the other two conditions

	        if (condition1) and (condition2 or condition3):
	            Process1
	        else: 
	            Process2
	        Nextprocess
	    

Example 4 ( Condition with non numeric)

A child is eligible to enter a ride if his/her age is between 4 to 10. Write a Python program to read child’s age, decide and display if the child is eligible for ride or not.

	age= input("What is your age? ")
        age= int(age)

        if(age > 3 and age < 11): 
            print(" Yes you are eligible to ride " )
        else:
            print ("Sorry you are not eligible to ride ")    

	   
	
Here is the code and its output:


For more details, please contact me here.
Date of last modification: 2021